package servlet.wxpay;

import pojo.Order;
import service.OrderService;
import service.impl.OrderServiceImpl;
import servlet.wxpay.sdk.MyConfig;
import servlet.wxpay.sdk.WXPay;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/WxPayOrderQueryServlet",name = "WxPayOrderQueryServlet")
public class WxPayOrderQueryServlet extends HttpServlet {

    private OrderService orderService = new OrderServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String orderNO = request.getParameter("orderNO");
        Order order = orderService.findByOrderNO(orderNO);

        //如果订单状态为1，说明已支付，直接返回SUCCESS
        //否则，去查一下微信后台，看看是否支付成功。
        //如果微信后台的状态为成功，则修改订单状态。
        if (order.getStatus()==1) {
            response.getWriter().print("SUCCESS");
        } else {

            try {
                MyConfig config = new MyConfig();
                WXPay wxpay = new WXPay(config);

                Map<String, String> data = new HashMap<String, String>();
                data.put("out_trade_no", order.getOrderNO());

                Map<String, String> resp = wxpay.orderQuery(data);
                System.out.println(resp);

                if ("SUCCESS".equals(resp.get("return_code")) && "SUCCESS".equals(resp.get("result_code"))) {
                    if ("SUCCESS".equals(resp.get("trade_state"))) {
                        order = orderService.findByOrderNO(orderNO);
                        //修改订单
                        if (order!=null && order.getStatus()==0) {
                            order.setPayType(2);
                            order.setStatus(1);
                            order.setTrade_no(resp.get("transaction_id"));
                            orderService.updateStatus(order);
                        }
                    }
                    response.getWriter().print(resp.get("trade_state"));
                } else {
                    System.out.println(resp.toString());
                    response.getWriter().print(resp.toString());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
